<template>
  <div class="schedule-list">
    <el-table
      :data="scheduleColumns"
      border
    >
      <el-table-column
        v-for="(column, index) in resourceAreaColumns"
        :key="index"
        :label="column.title"
        :prop="column.field"
        :width="index === 1 ? '100px' : ''"
        fixed
      >
        <template #header="scope">
          <div style="padding-left: 16px;">
            {{ scope.column.label }}
          </div>
        </template>

        <template v-slot="{ row }">

          <el-tooltip
            v-if="column.field === 'room'"
            placement="bottom"
            effect="light"
            popper-class="custom-tooltip"
          >
            <div
              style="padding-left: 16px;"
            >
              <span>
                {{ row[column.field] }}
              </span>
              <i class="el-icon-view" style="color: #1890FF;" />
            </div>
            <template #content>
              <div class="event-popover" style="width: 120px;">
                <div class="event-popover__title">
                  {{ row[column.field] }}
                </div>

                <div class="event-popover__info">
                  <i class="el-icon-notebook-2" />
                  <span>{{ row.notes }}</span>
                </div>
                <div class="event-popover__info">
                  <i class="el-icon-user" />
                  <span>{{ row.quantity }}人</span>
                </div>
                <div class="event-popover__info">
                  <el-tag :type="row.state === 1 ? 'success' : 'danger'">
                    {{ row.state === 1 ? '可用' : '不可用' }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-tooltip>

          <div
            v-else
            style="padding-left: 16px;"
          >
            {{ row[column.field] }}
          </div>
        </template>
      </el-table-column>

      <el-table-column width="1500px">
        <template #header="scope">
          <div
            class="flex"
          >
            <div
              v-for="(time, tIndex) in getTimRange"
              :key="'time_' + tIndex"
              :style="{
                width: `calc(100% / ${getTimRange.length})`
              }"
            >
              {{ tIndex === 0 ? '' : time }}
            </div>
          </div>
        </template>

        <template v-slot="{ row }">
          <div class="event-row">
            <div
              class="event-row__slots"
            >
              <div
                v-for="(slot, sIndex) in getSlotsCount"
                :key="'slot_' + sIndex"
                :style="{
                  width: `calc(100% / ${getSlotsCount})`
                }"
                class="event-row__slots__item"
              />
            </div>

            <div class="event-row__events">
              <el-tooltip
                v-for="(event, eIndex) in row?.events"
                :key="'event_' + eIndex"
                placement="bottom"
                effect="light"
                popper-class="custom-tooltip"
              >
                <div
                  class="event-row__events__item pointer"
                  :style="getEventStyle(event)"
                >
                  <span class="line-clamp-1">{{ event?.title }}</span>
                </div>
                <template #content>
                  <div class="event-popover">
                    <div class="event-popover__title">
                      {{ event?.title }}
                    </div>

                    <div class="event-popover__info">
                      <i class="el-icon-time" />
                      <span>{{ getTimeTitle(event?.start, event?.end) }}</span>
                    </div>
                    <div class="event-popover__info">
                      <i class="el-icon-user" />
                      <span>{{ event?.userName }}</span>
                    </div>
                    <div
                      class="flex event-popover__info"
                      style="justify-content: flex-end"
                    >
                      <el-button
                        type="primary"
                        size="mini"
                        @click="handleViewDetail(event.id)"
                      >
                        查看详情
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="操作"
        fixed="right"
        width="120px"
      >
        <template v-slot="{ row }">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-date"
            @click="handleReserve(row.id)"
          >
            预约
          </el-button>

          <el-button
            type="text"
            size="mini"
            @click="handleView(row)"
          >
            预约看板
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import dayjs from 'dayjs'

export default {
  name: 'ScheduleList2',
  props: {
    start: {
      type: Number,
      default: 7
    },

    end: {
      type: Number,
      default: 19
    },

    scheduleList: {
      type: Array,
      default: () => []
    },

    date: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      scheduleColumns: []
    }
  },
  computed: {
    getTimRange() {
      const timeRange = []
      for (let i = this.start; i <= this.end; i++) {
        const time = dayjs().hour(i).minute(0).second(0)
        timeRange.push(time.format('HH:mm'))
      }

      return timeRange
    },

    resourceAreaColumns() {
      return [
        { field: 'date', title: '日期' },
        { field: 'room', title: '会议室名称' }
      ]
    },

    getResourceDate() {
      return this.date ? dayjs(this.date).format('MM-DD') : dayjs().format('MM-DD')
    },

    getSlotsCount() {
      return this.getTimRange.length * 2
    }
  },
  watch: {
    scheduleList: {
      handler(newVal) {
        this.scheduleListFormat()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    scheduleListFormat() {
      this.scheduleColumns = this.scheduleList.map(item => {
        return {
          id: item.id,
          date: this.getResourceDate,
          room: item.name,
          quantity: item.quantity,
          notes: item.notes,
          state: item.state,
          events: item?.conference_room_reservation?.map(event => {
            return {
              id: event.id,
              title: event.reason,
              userName: event.user.username,
              start: event.start_time,
              end: event.end_time,
              resourceId: item.id
            }
          })
        }
      })
    },
    getEventStyle(event) {
      const startTime = new Date(event.start)
      const endTime = new Date(event.end)
      const startHour = startTime.getHours() + startTime.getMinutes() / 60
      const duration = (endTime - startTime) / (1000 * 60 * 60) // 持续时间（小时）
      const totalSlots = this.getSlotsCount // 总时间槽数（每小时2个）
      const slotWidth = 100 / totalSlots // 每个时间槽的宽度百分比
      const startSlot = (startHour - this.start) * 2 // 开始的时间槽索引
      const durationSlots = duration * 2 // 持续的时间槽数量
      const left = `${startSlot * slotWidth}%`
      const width = `${durationSlots * slotWidth}%`

      return {
        left,
        width,
        position: 'absolute',
        zIndex: 2
      }
    },

    getTimeTitle(start, end) {
      const startDate = dayjs(start)
      const endDate = dayjs(end)

      // 日期部分：MM月DD日（周X）
      const dateStr = `${startDate.format('MM月DD日')}（${'周日_周一_周二_周三_周四_周五_周六'.split('_')[startDate.day()]}）`

      // 时间部分：HH:mm~HH:mm
      const timeStr = `${startDate.format('HH:mm')}~${endDate.format('HH:mm')}`

      // 拼接结果
      return `${dateStr} ${timeStr}`
    },

    handleViewDetail(id) {
      this.$emit('viewDetail', id)
    },

    handleReserve(id) {
      this.$emit('reserve', id)
    },

    handleView(row) {
      console.log('row --------->', row)
      this.$router.push({
        name: 'weeklyView',
        query: {
          id: row.id,
          name: row.name
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.schedule-list {

  &__content {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
    border: 1px solid #EBEEF5;
  }

  .event-row {
    position: relative;
    height: 54px;

    &__slots {
      display: flex;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 1;

      &__item {
        height: 100%;
        border-right: 1px solid #EBEEF5;

        &:last-child {
          border-right: none;
        }
      }
    }

    &__events {
      height: 100%;
      display: flex;
      align-items: center;
      //position: absolute;
      //z-index: 2;
      &__item {
        //height: 100%;
        //line-height: 54px;
        padding: 12px 16px;
        //padding: 0 16px;
        background-color: #D9ECFF;
        border-radius: 4px;
        border-left: 4px solid #1890FF;
        color: #303133;
        font-size: 14px;
      }
    }
  }

  ::v-deep(.el-table__row) {
    .el-table__cell {
      padding: 0;
    }

    .cell {
      padding: 0;
    }
  }

  ::v-deep(.el-table__cell) {
    .cell {
      padding: 0;
    }
  }
}

.event-popover {
  &__title {
    color: #303133;
    font-size: 14px;
    font-weight: 700;
  }

  &__info {
    color: #606266;
    margin-top: 8px;
    font-size: 12px;
    > i {
      margin-right: 5px;
    }
  }
}
</style>
